`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date: 2024/06/19 17:01:35
// Design Name: 
// Module Name: Sync_10M
// Project Name: 
// Target Devices: 
// Tool Versions: 
// Description: 
// 
// Dependencies: 
// 
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
// 
//////////////////////////////////////////////////////////////////////////////////


module Sync_10M(
    input clk_40M,
    input clk_160M,
    input rst_n,
    input PPS_ref,
    (*mark_debug = "FALSE"*)(* KEEP = "FALSE" *) input [31:0] Fword,
    output clk10M,
     (*mark_debug = "FALSE"*)(* KEEP = "FALSE" *) output PPS_10M,
    output PPS_trigger
    );
//control_offset[31:7]

(*mark_debug = "FALSE"*)(* KEEP = "FALSE" *) reg value_valid;
(*mark_debug = "FALSE"*)(* KEEP = "FALSE" *) reg start;

    
    
    always@(posedge clk_40M or negedge rst_n)
    begin
        if(!rst_n) begin
            value_valid<=1'b0;
         end
         else if(Fword[31:0]==32'hFFFFFFFF)begin
            value_valid<=1'b1;
         end
    end    
    
    always@(posedge clk_40M or negedge rst_n)
    begin
        if(!rst_n) begin
            start<=1'b0;
         end
         else if(value_valid==1'b1 && PPS_ref==1'b1)begin
            start<=1'b1;
         end
    end    

    
    (*mark_debug = "FALSE"*)(* KEEP = "FALSE" *) reg [31:0] cnt;
    localparam cycle_cnt = 4000-1;
    
    always@(posedge clk_40M or negedge rst_n)
    begin
        if(!rst_n) begin
            cnt<= 32'd0;
         end
         else if (start==1'b1 && cnt<cycle_cnt) begin
            cnt<= cnt + 1'b1;
         end
         else begin
            cnt<= 32'd0;
         end
    end   
    
     (*mark_debug = "FALSE"*)(* KEEP = "FALSE" *) wire trigger;
    assign trigger = (cnt>2000 && cnt<2500)? 1:0;
    
    
    DDS u0(
    .clk(clk_160M),
    .rst_n(rst_n),
    .Fword(Fword), 
    .trigger(trigger),
    .data(clk10M)
    );

   (*mark_debug = "FALSE"*)(* KEEP = "FALSE" *) reg [31:0] cnt_10M;
    localparam cycle_cnt10M = 10000000-1;
    always@(posedge clk10M or negedge rst_n)
    begin
        if(!rst_n) begin
            cnt_10M<= 32'd0;
         end
         else if (start==1'b1 && cnt_10M<cycle_cnt10M) begin
            cnt_10M<= cnt_10M + 1'b1;
         end
         else begin
            cnt_10M<= 32'd0;
         end
    end   
    
 assign PPS_10M = (cycle_cnt10M==0)? 1 : 0;
 assign PPS_trigger = trigger;

endmodule
